//
//  CZEmoticonKeyBoard.swift
//  weibo
//
//  Created by Apple on 16/3/19.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  重用标记
private let EmoticonCollectionViewCellIdentifier = "EmoticonCollectionViewCellIdentifier"

//  表情键盘视图
class CZEmoticonKeyBoard: UIView, UICollectionViewDataSource, UICollectionViewDelegate{

    private lazy var emotionToolBar: CZEmoticonToolBar = {
        let toolBar =  CZEmoticonToolBar(frame: CGRectZero)
        //  注意循环引用
        toolBar.emoticonTypeSelectedClosure = {[weak self]  (type: EmoticonType)->() in
            let indexPath: NSIndexPath
            switch type {
            case .Recent:
                print("最近")
                indexPath = NSIndexPath(forItem: 0, inSection: 0)
            case .Default:
                print("默认")
                indexPath = NSIndexPath(forItem: 0, inSection: 1)
            case .Emoji:
                print("emoji")
                indexPath = NSIndexPath(forItem: 0, inSection: 2)
            case .Lxh:
                print("浪小花")
                indexPath = NSIndexPath(forItem: 0, inSection: 3)
            }
            self?.emotionCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition:UICollectionViewScrollPosition.Left, animated: false)
//            self?.pageControl.numberOfPages = CZEmoticonTools.shareEmoticonTools.allEmotions[indexPath.section].count
//            self?.pageControl.currentPage = indexPath.item
            self?.setPageControlDataWithIndexPath(indexPath)
        }
        return toolBar
    }()
    //  表情视图
    private lazy var emotionCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        //  设置每项直接的行间距和列间距都是0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        //  itemSize需要在layoutsubview里面去改
        //  设置水平方向滚动
        flowLayout.scrollDirection = .Horizontal
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        collectionView.registerClass(CZEmotionCollectionViewCell.self, forCellWithReuseIdentifier: EmoticonCollectionViewCellIdentifier)
        collectionView.backgroundColor = self.backgroundColor
        collectionView.dataSource = self
        collectionView.delegate = self
        //  水平的滚动条隐藏
        collectionView.showsHorizontalScrollIndicator = false
        //  垂直滚动条隐藏
        collectionView.showsVerticalScrollIndicator = false
        //  弹簧效果干部
        collectionView.bounces = false
        //  开启分页
        collectionView.pagingEnabled = true
        //  不管用
        //collectionView.alwaysBounceHorizontal = false

        return collectionView
    }()
    
    private lazy var pageControl: UIPageControl = {
        let pageCtrl = UIPageControl()
        
        pageCtrl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKeyPath: "_currentPageImage")
        pageCtrl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKeyPath: "_pageImage")
        //  如果只有一个则不显示
        pageCtrl.hidesForSinglePage = true
        
        return pageCtrl
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        //  主线程异步，等所有的主线的操作执行玩以后调用滚动到默认表情
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.emotionCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition:UICollectionViewScrollPosition.Left, animated: false)
            //  按钮选中
            self.emotionToolBar.showSelectButton(indexPath.section)
            //  pagecontrol 显示数据,因为如果只有一页就隐藏了，通过indexPath 设置pagecontrol数据，不是一样就显示出来控件
            self.setPageControlDataWithIndexPath(indexPath)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 
    override func layoutSubviews() {
        super.layoutSubviews()
        //  获取collectionview的布局对象,再次修改每项item的大小
        let flowLayout = emotionCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //  设置大小
        flowLayout.itemSize = CGSize(width: emotionCollectionView.width, height: emotionCollectionView.height)
        
    }
    
    private func setupUI() {
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        addSubview(emotionToolBar)
        addSubview(emotionCollectionView)
        addSubview(pageControl)
        emotionToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self)
            make.height.equalTo(37)
        }
        emotionCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self.emotionToolBar.snp_top)
        }
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(emotionToolBar)
            make.bottom.equalTo(emotionToolBar.snp_top)
            
        }
    }

    // MARK:    UICollectionViewDataSource
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonTools.shareEmoticonTools.allEmotions.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonTools.shareEmoticonTools.allEmotions[section].count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCollectionViewCellIdentifier, forIndexPath: indexPath) as! CZEmotionCollectionViewCell

        cell.indexPath = indexPath
        cell.emoticons = CZEmoticonTools.shareEmoticonTools.allEmotions[indexPath.section][indexPath.item]
        return cell
        
    }
    // MARK:    UIScorllViewDelegate
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let contentOffsetX = scrollView.contentOffset.x
        print(contentOffsetX)
        // 获取显示的cell
        let cells = emotionCollectionView.visibleCells()
        print(cells.count)
        var section: Int
        // 获取indexpath对应的section,设置按钮选中效果
        let indexPath: NSIndexPath
        // 获取第一个cell
        if cells.count == 2 {
            let firstCell = cells.first!
            let secondCell = cells.last!
            
            //  判断哪个显示的多
            let firstContentOffSetX = abs(firstCell.x - scrollView.contentOffset.x)
            let secondContentOffSetX = abs(secondCell.x - scrollView.contentOffset.x)
            
            if firstContentOffSetX < secondContentOffSetX {
                //  第一个显示的多
                indexPath = emotionCollectionView.indexPathForCell(firstCell)!
                
            } else {
                //  第二显示的多
                indexPath = emotionCollectionView.indexPathForCell(secondCell)!
            }
            section = indexPath.section
            //   根据section 去判断显示选中哪个按钮
            emotionToolBar.showSelectButton(section)
            

            
        } else {
            indexPath = emotionCollectionView.indexPathForCell(cells.first!)!
            section = indexPath.section
        }
        setPageControlDataWithIndexPath(indexPath)
        
        
    }
    
    private func setPageControlDataWithIndexPath(indexPath: NSIndexPath) {
        pageControl.numberOfPages = CZEmoticonTools.shareEmoticonTools.allEmotions[indexPath.section].count
        pageControl.currentPage = indexPath.item
    }
    
}
